/*
 * @Author: hongbin
 * @Date: 2022-11-20 21:28:45
 * @LastEditors: hongbin
 * @LastEditTime: 2022-12-01 11:39:43
 * @Description:世界消息
 */
import { FC, useCallback, useEffect, useRef, useState } from "react";
import styled, { css } from "styled-components";
import { get, post } from "../../api";
import { useAuth } from "../../context/AuthProvide";
import { SocketManager } from "../../socket";
import { flexCenter, FlexDiv } from "../../styled";
import NewsCard from "./NewsCard";

interface IProps {}

export interface INewsItem {
    _id: string;
    content: string;
    userName: string;
    userId: string;
}

/**
 * 世界消息 所有人均接收
 */
const WorldNews: FC<IProps> = () => {
    const { user } = useAuth();
    const inputRef = useRef<HTMLInputElement>(null);
    const newsContainerRef = useRef<HTMLDivElement>(null);
    const [list, setList] = useState<INewsItem[]>([]);
    const [show, setShow] = useState(true);

    const getNews = useCallback(async () => {
        const res = await get("/WorldNews/queryNews");
        if (res && res.data) {
            // console.log("世界消息:", res.data);
            setList(res.data);
        }
    }, []);

    const send = useCallback(async () => {
        const content = inputRef.current!.value;
        if (!content) return;

        const news = {
            content,
            userId: user._id,
            userName: user.name,
        };
        const { data } = await post("/WorldNews/send", news);
        console.log("发送世界消息:", data);
        if (!data.code) {
            inputRef.current!.value = "";
            SocketManager.emit("sendWorldNews", data);
            setList((prev) => [...prev, data]);
        }
    }, [user]);

    const newNewsListener = useCallback((info: INewsItem) => {
        console.log("监听到新世界消息：", info);
        setList((prev) => [...prev, info]);
    }, []);

    useEffect(() => {
        getNews();
        SocketManager.listen("newWorldNews", newNewsListener);
        return () => {
            // SocketManager.removeListen("newWorldNews", newNewsListener);
        };
    }, [getNews, newNewsListener]);

    /**
   内容变化时自动滚动到最下面
   */
    useEffect(() => {
        newsContainerRef.current?.scrollTo(0, newsContainerRef.current.scrollHeight);
    }, [list]);

    const togglePlane = useCallback(() => {
        setShow((state) => !state);
    }, []);

    return (
        <Container show={show}>
            <header>
                <span>世界消息</span>
                <div onClick={togglePlane}>
                    <svg
                        viewBox="0 0 1024 1024"
                        version="1.1"
                        xmlns="http://www.w3.org/2000/svg"
                        p-id="3439"
                        width="16"
                        height="16"
                    >
                        <path
                            d="M872 572H266.8l144.3-183c4.1-5.2 0.4-13-6.3-13H340c-9.8 0-19.1 4.5-25.1 12.2l-164 208c-16.5 21-1.6 51.8 25.1 51.8h696c4.4 0 8-3.6 8-8v-60c0-4.4-3.6-8-8-8z"
                            p-id="3440"
                        ></path>
                    </svg>
                    {show ? "收起" : "展开"}
                </div>
            </header>
            <main ref={newsContainerRef}>
                {list.map((news: INewsItem) => (
                    <NewsCard key={news._id} news={news} />
                ))}
            </main>
            <FlexDiv>
                <input type="text" ref={inputRef} />
                <button onClick={send}>发送</button>
            </FlexDiv>
        </Container>
    );
};

export default WorldNews;

const Container = styled.div<{ show: boolean }>`
    max-width: 300px;
    position: absolute;
    bottom: 1vmax;
    left: 1vmax;
    /* background: #ffffff44; */
    background: #20740e;
    width: 15vmax;
    height: 15vmax;
    border-radius: 1vmax;
    z-index: 11;
    overflow: hidden;
    /* --color: #7fc16b;
    box-shadow: ${(props) => props.theme.boxShadow}; */
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    transform: translateY(0);
    transition: transform 0.3s ease;

    & > main {
        flex: 1;
        overflow: hidden scroll;
        margin: 0.5vmax;
        margin-top: 0;
        border-radius: 1vmax;
    }

    input {
        height: 2vmax;
        padding-left: 1vmax;
        border: none;
        background: #17610c;
        width: 70%;
        transition: 0.3s;
        outline: none;

        :focus {
            background: #0c4104;
            color: #fff;
        }
    }
    button {
        cursor: pointer;
        width: 30%;
        background: #1e6c17;
        color: #fffae5;
        transition: 0.3s;
        border: none;
        :hover {
            font-weight: bold;
            background: #0d4904;
        }
    }
    header {
        font-size: min(14px, 1vw);
        color: #c8deb2;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-left: 0.5vmax;
        padding-top: 2px;
        svg {
            fill: #c8deb2;
            transform: rotate(-90deg);
            transition: transform 0.3s linear;
            width: 1vw;
            height: 1vw;
        }
        div {
            padding: 0 0.5vw;
            transition: 0.3s;
            cursor: pointer;
            ${flexCenter};
            border-bottom-left-radius: 0.5vw;
            :hover {
                background-color: #0d4904;
                letter-spacing: 2px;
            }
        }
    }
    ${({ show }) =>
        !show &&
        css`
            transform: translateY(95%);
            header {
                svg {
                    transform: rotate(90deg);
                }
            }
        `};
`;
